import {resolve} from 'path';
import {defineConfig, loadEnv} from 'vite';
import vue2 from '@vitejs/plugin-vue2';
import {viteCommonjs} from '@originjs/vite-plugin-commonjs'
import commonjs from '@rollup/plugin-commonjs'
import requireSupport from 'vite-plugin-require-support';
import langJsx from 'vite-plugin-lang-jsx'

export default ({mode}) => {
    const {VITE_PORT, VITE_BASE_URL} = loadEnv(mode, process.cwd());

    return defineConfig({
        base: VITE_BASE_URL,
        plugins: [
            commonjs(), // 打包node_modules中的commonjs模块
            vue2(),
            viteCommonjs(), // 开发模式下兼容commonjs
            langJsx(),
            requireSupport({
                filters: /.ts$|.js$|.jsx$|.tsx$|.vue$/
            }),
        ],
        resolve: {
            alias: {
                '@': resolve(__dirname, './src'),
            },
            extensions: ['.js', '.vue', '.json'],
        },
        define: {
            'process.env': process.env
        },
        css: {
            preprocessorOptions: {
                less: {
                    modifyVars: {
                        hack: `true; @import (reference) "${resolve('src/style/variables.less')}";`,
                    },
                    math: 'strict',
                    javascriptEnabled: true,
                },
            },
        },
        server: {
            // 是否开启 https
            https: false,
            // 端口号
            port: VITE_PORT,
            // 监听所有地址
            host: '0.0.0.0',
            // 服务启动时是否自动打开浏览器
            open: false,
            // 允许跨域
            cors: true,
            hmr: {
                overlay: false  // 关闭热更新时的错误覆盖层
            },
            // 自定义代理规则
            proxy: {
                '/api': {
                    // target: 'https://oj.rui-ya.com/',
                    target: 'http://localhost:6688/',
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, '/api'),
                },
            },
        },
        build: {
            // 设置最终构建的浏览器兼容目标
            target: 'es2015',
            // 构建后是否生成 source map 文件
            sourcemap: false,
            //  chunk 大小警告的限制（以 kbs 为单位）
            chunkSizeWarningLimit: 2000,
            // 启用/禁用 gzip 压缩大小报告
            reportCompressedSize: false,
            commonjsOptions: {
                include: []  // 打包node_modules中的commonjs模块
            },
            rollupOptions: {
                output: {
                    strict: false
                }
            }
        },
    });
};
